<?php

// No direct access to this file
defined('_JEXEC') or die('Restricted access');
JTable::addIncludePath(JPATH_COMPONENT.DIRECTORY_SEPARATOR.'tables');

class KetnoiModelUserprofile extends JModelLegacy
{
	public function getTable($type = 'Userprofile', $prefix = 'KetnoiTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}
	
	function loadGridData($limitstart,$limit,$where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("*");
        $query->from("#__user_profile");
        $query->where($where);
        $query .= " order by id DESC ";
        $query .= " limit $limitstart,$limit";  
        $db->setQuery($query);
        $result = $db->loadObjectList();
        return $result; 
    }
    
	function loadAllGridData($where)
    {
        $db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)");
        $query->from("#__user_profile");
        $query->where($where); 
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result; 
    }
       
    
	function checkMaExists()
    {
    	$ma = JRequest::getVar("ma");
    	$oldval = JRequest::getVar("oldval","");
    	if(strtolower($ma) == strtolower($oldval))
    	{
    		return false;
    	}
    	$db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)");
        $query->from("#__user_profile");
        $query->where("is_delete = 0 and ma = '$ma'");
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result > 0;
    }
    
	function checkTenExists()
    {
    	$ten = JRequest::getVar("hoten");
    	$oldval = JRequest::getVar("oldval","");
    	if(strtolower($ten) == strtolower($oldval))
    	{
    		return false;
    	}
    	$db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)");
        $query->from("#__user_profile");
        $query->where("is_delete = 0 and hoten = '$ten'");
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result > 0;
    }
    
	function checkUsername()
    {
    	$username = JRequest::getVar("username");
    	$db = JFactory::getDbo();
        $query = $db->getQuery(true);
        $query->select("count(*)");
        $query->from("#__users");
        $query->where("block = 0 and username = '$username'");
        $db->setQuery($query);
        $result = $db->loadResult();
        return $result > 0;
    }
    
	function loadData($id)
	{
		$table = $this->getTable();
		$table->load($id);
		return $table;
	}
	
	function loadDataUser($profile_id)
	{
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		$query->select("*")
			  ->from("#__users")
			  ->where("profile_id = $profile_id");
		$db->setQuery($query);
		return $db->loadObject();	  
	}	
	
	function save()
	{
		global $app;
    	$result = array("success"=>true,"error"=>"");
    	
    	$arr_upload = Utility::uploadImages("file");
    	if(!$arr_upload["success"])
    	{
    		return $arr_upload;
    	}else 
    	{
    		$old_file = JRequest::getVar("old_file","");
    		if(!empty($old_file))
    		{
    			$old_file = json_decode($old_file,true);
    			$delete_file = json_decode(JRequest::getVar("delete_file"),true);
    			$img_dir = JPATH_SITE.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'fileupload'.DIRECTORY_SEPARATOR;
    			
    			foreach ($old_file as $file)
    			{
    				if(!in_array($file, $delete_file))
    				{
    					$arr_upload["data"][] = $file;
    				}else 
    				{
    					if(JFile::exists($img_dir.$file))
    					{
    						JFile::delete($img_dir.$file);
    					}
    				}
    			}
    		}
    		$images = json_encode($arr_upload["data"]);
    		$table = $this->getTable();
	    	$post = JRequest::get("post");
	    	$post["hinhanh"] = $images;
			$table = Utility::save($table, $post);
			$result["id"] = $table->id;
			$result["hoten"] = $table->hoten;
			$result["ma"] = $table->ma;
			//process user
			$isUserCheck = $post["isUserCheck"];
			$isNewUser = empty($post["userid"]);
			if($isUserCheck)
			{
				$table_user = $this->getTable("Users");
				$arr_user = array();
				$arr_user["username"] =  $post["username"];
				$arr_user["group_id"] =  $post["group_id"];
				$arr_user["profile_id"] =  $table->id;
				$arr_user["email"] = $table->email;
				$arr_user["name"] = $table->hoten;
				if($isNewUser)
				{
					$password = $post["password"];
	    			jimport('joomla.user.helper');
			        $salt   = JUserHelper::genRandomPassword(32);
			        $crypted  = JUserHelper::getCryptedPassword(trim($password),$salt);
			        $cpassword = $crypted.':'.$salt;
			        $arr_user["password"] =  $cpassword;     
				}else 
				{
					$arr_user["id"] = $post["userid"];
					if(trim($post["password"]) != "")
					{
						$password = $post["password"];
		    			jimport('joomla.user.helper');
				        $salt   = JUserHelper::genRandomPassword(32);
				        $crypted  = JUserHelper::getCryptedPassword(trim($password),$salt);
				        $cpassword = $crypted.':'.$salt;
				        $arr_user["password"] =  $cpassword; 
					}
				}
				
				$table_user = Utility::save($table_user, $arr_user);
				$user_id = $table_user->id;
				$group_id = $post["group_id"];
				if($isNewUser)
				{
					$this->insertUserGroup($user_id, 2);
					$this->insertUserGroup($user_id, $group_id);
				}else 
				{
					$this->insertUserGroup($user_id, $group_id);
				}
				
			}
			
			
    	}
    	return $result;
	}
	
	function insertUserGroup($user_id,$group_id)
	{
		$db = JFactory::getDbo();
		$query = "delete from #__user_usergroup_map where user_id = $user_id and group_id <> 2";
		$db->setQuery($query);
		$db->query();
		$query = "insert #__user_usergroup_map values($user_id,$group_id)";
		$db->setQuery($query);
		$db->query();
	}
	
	function delete()
	{
		$id = JRequest::getVar("id");
		//$row = $this->loadData($id);
		//$images = $row->hinhanh;
		$user = $this->loadDataUser($id);
		$userid = $user->id;
		
		$db = JFactory::getDbo();
		$query = "update #__user_profile set is_delete = 1 where id = $id";
		$db->setQuery($query);
		$db->query();
		
		/*
		if(!empty($images))
		{
			$img_dir = JPATH_SITE.DIRECTORY_SEPARATOR.'images'.DIRECTORY_SEPARATOR.'fileupload'.DIRECTORY_SEPARATOR;
			$arr_image = json_decode($images);
			if(count($arr_image) > 0)
			{
				foreach ($arr_image as $img)
				{
					if(JFile::exists($img_dir.$img))
					{
						JFile::delete($img_dir.$img);
					}
				}		
			}
		}*/
		
		if(!empty($userid))
		{
			$query = "update #__users set is_delete = 1,block = 1 where id = $userid";
			$db->setQuery($query);
			$db->query();
		}
	}
	
	
}
